package com.gdcontrol.desktop.visao.consulta;

import com.gdcontrol.desktop.controle.consulta.ControleConsultaPrescricao;
import com.gdcontrol.desktop.controle.manutencao.ControleManutencaoPrescricao;
import com.gdcontrol.desktop.util.tablemodel.PrescricaoTableModel;
import com.gdcontrol.desktop.visao.manutencao.VisaoManutencaoPrescricao;
import com.gdcontrol.entidade.Prescricao;
import java.awt.event.KeyEvent;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author gustavo
 */
public class VisaoConsultaPrescricao extends VisaoConsultaPadrao {

    public final static String OPCAO_ID = "ID";
    public final static String OPCAO_DATA_INICIO = "Data Início";
    public final static String OPCAO_DATA_FIM = "Data Fim";
    public final static String OPCAO_NOME_MEDICO = "Nome Médico";
    public final static String OPCAO_NOME_MEDICACAO = "Nome Medicação";
    
    /**
     * Creates new form VisaoConsultaPrescricao
     */
    public VisaoConsultaPrescricao(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        carregaPrescricoes();
        getOpcoesPesquisa();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        cbCampoPesquisa = new javax.swing.JComboBox();
        edPesquisa = new javax.swing.JTextField();
        btPesquisar = new javax.swing.JButton();
        btNovo = new javax.swing.JButton();
        btAlterar = new javax.swing.JButton();
        edExcluir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbPrescricao = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Consulta Prescrição");

        jLabel1.setText("Campo Pesquisa:");

        jLabel2.setText("Pesquisar:");

        edPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                edPesquisaKeyPressed(evt);
            }
        });

        btPesquisar.setText("Pesquisar");
        btPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisarActionPerformed(evt);
            }
        });

        btNovo.setText("Novo");
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });

        btAlterar.setText("Alterar");
        btAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btAlterarActionPerformed(evt);
            }
        });

        edExcluir.setText("Excluir");
        edExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                edExcluirActionPerformed(evt);
            }
        });

        tbPrescricao.setModel(tableModelPrescricao);
        tbPrescricao.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbPrescricaoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbPrescricao);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(cbCampoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(edPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 251, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btPesquisar))))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btNovo)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btAlterar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(edExcluir)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbCampoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(edPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btPesquisar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btNovo)
                    .addComponent(btAlterar)
                    .addComponent(edExcluir))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 341, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisarActionPerformed
        if(!edPesquisa.getText().isEmpty()){
            tableModelPrescricao.limpar();
            String pesquisa = (String) cbCampoPesquisa.getSelectedItem();
            switch(pesquisa){
                case OPCAO_ID:
                    try{
                        filtraId(Integer.parseInt(edPesquisa.getText()));
                    }catch(NumberFormatException e){}
                    break;
                case OPCAO_DATA_INICIO:
                    filtraDataInicio(edPesquisa.getText());
                    break;
                case OPCAO_DATA_FIM:
                    filtraDataFim(edPesquisa.getText());
                    break;
                case OPCAO_NOME_MEDICO:
                    filtraNomeMedico(edPesquisa.getText());
                    break;
                case OPCAO_NOME_MEDICACAO:
                    filtraNomeComercialMedicacao(edPesquisa.getText());
                    break;
            }
            tableModelPrescricao.fireTableDataChanged();
        }else{
            carregaPrescricoes();
        }
    }//GEN-LAST:event_btPesquisarActionPerformed

    private void edPesquisaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_edPesquisaKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btPesquisarActionPerformed(null);
        }
    }//GEN-LAST:event_edPesquisaKeyPressed

    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        VisaoManutencaoPrescricao manutencao = new VisaoManutencaoPrescricao(null, true);
        manutencao.setVisible(true);
        carregaPrescricoes();
    }//GEN-LAST:event_btNovoActionPerformed

    private void btAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btAlterarActionPerformed
        int indice = tbPrescricao.getSelectedRow();
        if (indice >= 0) {
            VisaoManutencaoPrescricao manutencao = new VisaoManutencaoPrescricao(null, true);
            ControleManutencaoPrescricao controleManutencao = (ControleManutencaoPrescricao) manutencao.getControle();
            controleManutencao.setModelo(tableModelPrescricao.getPrescricao(indice));
            controleManutencao.setTela(manutencao);
            controleManutencao.carregaTela();
            manutencao.setVisible(true);
            carregaPrescricoes();
        }
    }//GEN-LAST:event_btAlterarActionPerformed

    private void tbPrescricaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbPrescricaoMouseClicked
        if (evt.getClickCount() == 2) {
            btAlterarActionPerformed(null);
        }
    }//GEN-LAST:event_tbPrescricaoMouseClicked

    private void edExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edExcluirActionPerformed
        int indice = tbPrescricao.getSelectedRow();
        if (indice >= 0) {
            int opcao = JOptionPane.showConfirmDialog(this, "Confirma exclusão da Prescrição selecionada?");
            if(opcao == JOptionPane.YES_OPTION){
                getControle().excluir(tableModelPrescricao.getPrescricao(indice));
                carregaPrescricoes();
            }
        }
    }//GEN-LAST:event_edExcluirActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaPrescricao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaPrescricao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaPrescricao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VisaoConsultaPrescricao.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                VisaoConsultaPrescricao dialog = new VisaoConsultaPrescricao(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btAlterar;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btPesquisar;
    private javax.swing.JComboBox cbCampoPesquisa;
    private javax.swing.JButton edExcluir;
    private javax.swing.JTextField edPesquisa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbPrescricao;
    // End of variables declaration//GEN-END:variables

    ControleConsultaPrescricao controle = new ControleConsultaPrescricao();
    PrescricaoTableModel tableModelPrescricao = new PrescricaoTableModel();
    
    private void carregaPrescricoes() {
        tableModelPrescricao.limpar();
        for (Prescricao prescricao : (List<Prescricao>) getControle().listar()) {
            tableModelPrescricao.addPrescricao(prescricao);
        }
        tableModelPrescricao.fireTableDataChanged();
    }
    
    private void filtraId(int id){
        Prescricao prescricao = getControle().filtraId(id);
        if(prescricao != null){
            tableModelPrescricao.addPrescricao(prescricao);
        }
    }
    
    private void filtraDataInicio(String dataInicio){
        for (Prescricao prescricao : (List<Prescricao>) getControle().filtraDataInicio(dataInicio)) {
            tableModelPrescricao.addPrescricao(prescricao);
        }
    }
    
    private void filtraDataFim(String dataFim){
        for (Prescricao prescricao : (List<Prescricao>) getControle().filtraDataFim(dataFim)) {
            tableModelPrescricao.addPrescricao(prescricao);
        }
    }
    
    private void filtraNomeMedico(String nome){
        for (Prescricao prescricao : (List<Prescricao>) getControle().filtraNomeMedico(nome)) {
            tableModelPrescricao.addPrescricao(prescricao);
        }
    }
    
    private void filtraNomeComercialMedicacao(String nome){
        for (Prescricao prescricao : (List<Prescricao>) getControle().filtraNomeComercialMedicacao(nome)) {
            tableModelPrescricao.addPrescricao(prescricao);
        }
    }
    
    @Override
    public void getOpcoesPesquisa() {
        Vector comboBoxItems = new Vector();
        comboBoxItems.add(OPCAO_ID);
        comboBoxItems.add(OPCAO_DATA_INICIO);
        comboBoxItems.add(OPCAO_DATA_FIM);
        comboBoxItems.add(OPCAO_NOME_MEDICO);
        comboBoxItems.add(OPCAO_NOME_MEDICACAO);
        final DefaultComboBoxModel model = new DefaultComboBoxModel(comboBoxItems);
        this.cbCampoPesquisa.setModel(model);
    }

    @Override
    public ControleConsultaPrescricao getControle() {
        return this.controle;
    }
}
